package com.chen.common.websocket.handler;

import lombok.SneakyThrows;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket消息通信抽象类
 * @author: Long
 * @date: 2023/8/6 21:17
 **/
public abstract class AbsWebSocketHandler {

    /**
     * K: 端点:客户端IP
     * V: WebSocketSession
     */
    public final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    /**
     * 接收消息事件
     */
    public abstract void handleTextMessage(TextMessage message);

    /**
     * 发送消息
     */
    @SneakyThrows
    public void sendMessageAll(String msg){
        for (WebSocketSession session : sessionMap.values()) {
            session.sendMessage(new TextMessage(msg));
        }
    }
}
